package net.seehope.foodie.controller.async;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

//这是个监听器，监听的是服务启动事件，监听器不需要配置，直接加到容器就行
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent>{
	
	@Autowired
	private MockQueue queue;
	
	@Autowired
	private DeferredResultHolder holder;
	
	private static final Logger log = LoggerFactory.getLogger(QueueListener.class);


	
	@Override
	//这个方法会在服务一启动时就被调用
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		//开一个新的线程
		new Thread(()->{
			//在这个线程里，监听队列
			while(true) {
				if(StringUtils.isNotEmpty(queue.getCompleteOrder())) {
					String orderId = queue.getCompleteOrder();
					
					log.info("监听器获取到了队列中的返回结果，订单号为{}--",orderId);
					//将结果中的map对应的orderId找到，将result作为其value塞进去
					holder.getMap().get(orderId).setResult(orderId);
					//清空队列
					queue.setCompleteOrder(null);
				}else {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
				
		}).start();
		
		
		new Thread(()->{
			
		//一直在监听这个队列
		while (true) {
			//如果已处理完的订单不为空，获取到这个订单
			if (!StringUtils.isEmpty(queue.getCompleteOrder())) {
				String orderId = queue.getCompleteOrder();
				log.info("监听器获取到了队列的返回结果，订单号为{}--",orderId);
				holder.getMap().get(orderId).setResult(orderId);
				//清空队列
				queue.setCompleteOrder(null);
			}else {
				//不断的获取
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		}).start();
		
		
		
		
	}

}
